# coding=utf-8
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser
from django.db import close_old_connections
from rest_framework_jwt.authentication import jwt_decode_handler


class QueryAuthMiddleware:

	def __init__(self, inner):
		self.inner = inner

	def __call__(self, scope):
		close_old_connections()
		token = scope["query_string"]
		token = token.decode("utf-8")
		user = AnonymousUser()
		if token:
			user = authenticate(token)

		return self.inner(dict(scope, user=user))


def authenticate(jwt_value):
	try:
		payload = jwt_decode_handler(jwt_value)
	except Exception:
		user = AnonymousUser()
		return user

	user = authenticate_credentials(payload)

	return user


def authenticate_credentials(payload):
	username = payload.get('username')
	try:
		User = get_user_model()
		user = User.objects.get(username=username)
	except Exception:
		user = AnonymousUser()
	return user
